package com.partsoft.spring.zks;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.zkoss.xel.VariableResolver;
import org.zkoss.xel.XelException;
import org.zkoss.zk.ui.Executions;

import com.partsoft.utils.StringUtils;

public class SpringVariableResolver implements VariableResolver {

	protected static final String SPRING_VAR_PREFIX = "spring";

	public Object resolveVariable(String varName) throws XelException {
		if (!StringUtils.hasText(varName) || !(varName.startsWith(SPRING_VAR_PREFIX)))
			return null;
		ServletContext sct = Executions.getCurrent().getDesktop().getWebApp().getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sct);
		if (ObjectUtils.nullSafeEquals(SPRING_VAR_PREFIX, varName)) {
			return ctx;
		}
		Object result = null;
		if (varName.length() > (SPRING_VAR_PREFIX.length() + 1)
				&& (varName.charAt(SPRING_VAR_PREFIX.length()) == '$' || 
						varName.charAt(SPRING_VAR_PREFIX.length()) == '_' ||
						varName.charAt(SPRING_VAR_PREFIX.length()) == '.')) {
			try {
				varName = varName.substring(SPRING_VAR_PREFIX.length() + 1, varName.length());
				if (ctx.containsBean(varName)) {
					result = ctx.getBean(varName);
				}
			} catch (Exception e) {
			}
		}
		return result;
	}
}
